package com.starinside.wp.components;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.starinside.wp.components.redis.RedisService;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.repository.WxUserRepository;
import com.starinside.wp.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.starinside.wp.foundation.constant.CommonConstant.Platform.WEB;
import static com.starinside.wp.foundation.constant.RedisConstant.*;
import static com.starinside.wp.foundation.model.ErrorCode.TICKET_EXPIRED;


/**
 * @author: Fablenas
 */
@Component("memVerificationCache")
@Slf4j
public class MemVerificationCache {

    private static final String TICKET_FORMAT = "%s-%s-%s";

    @Autowired
    private RedisService redisService;

    @Autowired
    private WxUserRepository wxUserRepository;

    public static ObjectMapper objectMapper = new ObjectMapper();

//    @Autowired
//    private SsoCallService ssoCallService;

    public String getWxUserId(String ticket) {
        if (StringUtils.isBlank(ticket))
            throw new BusinessException(TICKET_EXPIRED, "无效的ticket，请重新登录!");

        String value = redisService.getValue(ticket);
        if (StringUtils.isBlank(value))
            throw new BusinessException(TICKET_EXPIRED, "登录已过期，请重新登录!");
        Map cache = null;
        try {
            cache = objectMapper.readValue(value, HashMap.class);
        } catch (IOException e) {
            log.error("get cache json parse object error!!!!!");
            throw new BusinessException(TICKET_EXPIRED, "登录已过期，请重新登录!");
        }
        if (cache.get(STAFF_KEY) == null)
            throw new BusinessException(TICKET_EXPIRED, "登录已过期，请重新登录!");

        String staffId = cache.get(STAFF_KEY).toString();

        refreshTime(ticket);

        return staffId;

    }

//    public String getAreaId( String ticket) {
//        return getStaff(ticket).getAreaId();
//    }
//
//    public StaffDTO getStaff(String ticket) {
//        return ssoCallService.getStaffDTO(ticket);
//    }

    public String produceTicket(String staffId, Integer channel) {
        String key = SignUtil.mySign(staffId + channel, "utf-8");
//        redisService.deleteLike(key + "-" + channel);
        String ticket = String.format(TICKET_FORMAT, key, channel, System.currentTimeMillis());
        Map map = new HashMap();
        map.put(STAFF_KEY, staffId);
        Long expiredTime = 0L;
        try {
            if (channel == WEB.codeOf()) {
                expiredTime = WEB_TICKET_EXPIRED_TIME;
            }else {
                expiredTime = PHONE_TICKET_EXPIRED_TIME;
            }
            redisService.saveValue(ticket, expiredTime, objectMapper.writeValueAsString(map));
        } catch (JsonProcessingException e) {
            log.error("produce ticket parseJson error!!!!!");
        }
        return ticket;
    }
 
    public Map getCacheMap(@NotBlank String ticket) {
        try {
            String value = redisService.getValue(ticket);
            if (StringUtils.isBlank(value))
                return null;
            Map response = objectMapper.readValue(value, HashMap.class);
            response.put("ticket", ticket);
            return response;
        } catch (IOException e) {
            log.error("get cache json parse object error!!!!!");
        }
        return null;
    }

    public boolean refreshTime(String ticket){
        redisService.refreshTime(ticket, PAD_TICKET_EXPIRED_TIME);
        return true;
    }


    public WxUser getWxUser(String ticket) {
        String wxUserId = getWxUserId(ticket);

        return wxUserRepository.getOne(wxUserId);
    }

}
